import React, { Component } from 'react';
import { Modal } from 'antd';
import { config } from 'utils'
import newWebchannel from '../../../public/qwebchannel'
import md5 from "md5";
window.md5 = md5
const { host, api } = config
const { fileUpload } = api
export default class CrossBrowserDriver extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      videoType: 0,
      confirmLoading: false,
      idcard: null,
    };
  }
  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextProps.key != this.props.key ||
      nextState.visible != this.state.visible ||
      nextState.confirmLoading != this.state.confirmLoading
    );
  }
  openVideoMain(type, data) {
    this.setState({
      videoType: type,
      visible: true,
      formData: data
    })
  }
  openSocket() {
    let that = this
    let socket = window.socket
    socket.onclose = function () {
      console.error("web channel closed");
    };
    socket.onerror = function (error) {
      console.error("web channel error: " + error);
    }
    socket.onopen = function () {
      newWebchannel.QWebChannel(socket, function (channel) {
        //获取注册的对象
        window.dialog = channel.objects.dialog;
        window.dataURLtoFile = function (dataurl, filename = 'file') {
          const mime = "image/png ";
          const suffix = "png "
          let bstr = atob(dataurl)
          let n = bstr.length
          let u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          return new File([u8arr], `${filename}.${suffix}`, {
            type: mime
          })
        }

        window.getBase64Image = function (img) {
          var canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height;
          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, img.width, img.height);
          var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
          var dataURL = canvas.toDataURL("image/" + ext);
          return dataURL;
        }

        //网页关闭函数
        window.onbeforeunload = function () {
          dialog.get_actionType("closeSignal");
        }
        window.onunload = function () {
          dialog.get_actionType("closeSignal");
        }
        //单次二代证阅读
        if (document.getElementById("NFCIdentify")) {
          document.getElementById("NFCIdentify").onclick = function () {
            dialog.get_actionType("singleReadIDCard");
          };
        }
        if (document.getElementById("NFCIdentify")) {
          document.getElementById("NFCIdentify").onclick = function () {
            dialog.get_functionTypes("getIdcardImage", "1", "", "");
          };
        }
        //服务器返回消息
        dialog.sendPrintInfo.connect(function (message) {
          let that_this = that
          // //读取二代证头像返回信息
          if (message.indexOf("IDcardInfo:") >= 0) {
            let messageRuslt = message.replace("IDcardInfo:", "")
            let IDcardArry = messageRuslt.trim().split(/\s+/)
            const idcard = {
              name: IDcardArry[0],
              sex: IDcardArry[1],
              nativePlace: IDcardArry[2],
              dateOfBirth:
                IDcardArry[3] +
                '/' +
                IDcardArry[4] +
                '/' +
                IDcardArry[5],
              address: IDcardArry[6],
              cardID: IDcardArry[7],
              authority: IDcardArry[8],
              validStart: IDcardArry[9]+'.'+ IDcardArry[10] +'.'+ IDcardArry[11] + '-' + IDcardArry[12]+'.'+ IDcardArry[13] +'.'+ IDcardArry[14] ,
              validEnd: IDcardArry[12],
            };
            that_this.props.readCard(idcard)
            return;
          } else if (message.indexOf("idFaceInfo:") >= 0) {
            let messageRuslt = message.replace("idFaceInfo:", "")
            that_this.props.readCard(messageRuslt)
          } else if (message.indexOf("fileBase64:") >= 0) {
            var value = message.substr(11);
            that_this.props.onBiokey && that_this.props.onBiokey(value);
            // return;
          } else if (message.indexOf("BarcodeInfo:") >= 0) {
            //格式为 "BarcodeInfo:" + "个数\n" + "识别结果\n"。每个每个结果后有换行符
            var BarcodeInfo = message.substr(12);
            let companyCardArry = BarcodeInfo.trim().split(/\s+/)
            const orgData = {
              name:companyCardArry[3].substr(3),
              creditCode:companyCardArry[1].substr(9),
              // type: data['类型']['words'],
              // address: data['地址']['words'],
              // legalPerson: data['法人']['words'],
              // registeredCapital: data['注册资本']['words'],
              establishmentTime:companyCardArry[5].substr(5),
              // businessTerm: data['有效期']['words'],
              // businessScope: data['经营范围']['words'],
            }
            that_this.props.onBarcodeDecode && that_this.props.onBarcodeDecode(orgData)
          }
          //指纹模板数据返回
          if (message.indexOf("GetBiokeyTemplate_success!") >= 0) {
            var name = message.substr(26);
            dialog.get_functionTypes("getFileBase64", name, "", "");
          }
        });
        dialog.send_priImgData.connect(function (message) {
          var element = document.getElementById("bigPriDev");
          if (element) {
            element.src = "data:image/jpg;base64," + message;
          }
        });
        dialog.send_subImgData.connect(function (message) {
          var element = document.getElementById("bigSubDev");
          if (element) {
            element.src = "data:image/jpg;base64," + message;
          }
        });
        // 副摄像头
        dialog.send_subPhotoData.connect(function (message) {
          let that_this = that
          const videoType = that_this.state.videoType
          if (videoType == 1) {
            that_this.props.onAssistPicture && that_this.props.onAssistPicture(message);
          }
        });
        dialog.send_priPhotoData.connect(function (message) {
          let that_this = that
          const { userId, localId, partyNumber, type, dataType } = that_this.state.formData
          const videoType = that_this.state.videoType
          if (videoType == 0) {
            const md5 = window.md5(message)
            const file = window.dataURLtoFile(message)
            const formdata = new FormData();
            formdata.append('file', file);
            formdata.append('userId', userId)
            formdata.append('localId', localId)
            formdata.append('partyNumber', partyNumber)
            formdata.append('type', type)
            formdata.append('dataType', dataType)
            formdata.append('fileMd5', md5)
            const url = host + fileUpload;
            fetch(url, {
              method: 'POST',
              body: formdata,
            }).then(res => that_this.props.onTakePicture && that_this.props.onTakePicture(res)).catch(error => console.log(error));
          }else if(videoType == 3){
            const img = 'data:image/jpeg;base64,' + message;
            that_this.props.onTakePictureBase64 && that_this.props.onTakePictureBase64(img);
          }
        });
        dialog.html_loaded("faceDetect_two");
      })
    }
    socket.onopen()
  }
  handleCancel() {
    const videoType = this.state.videoType
    if (videoType == 0) {
      var element = document.getElementById("bigPriDev");
      element.src = ""
    } else if (videoType == 1) {
      var element = document.getElementById("bigSubDev");
      element.src = ""
    }
    this.setState({
      visible: false,
    });
  }
  //指纹   
  readFinger() {
    dialog.get_actionType("InitBiokey");
    dialog.get_actionType("GetBiokeyTemplate");
  }
  componentWillMount() {
    this.openSocket();
  }

  handleOk() {
    const videoType = this.state.videoType
    if (videoType == 0 ||videoType == 3) {
      dialog.photoBtnClicked("primaryDev_");
      dialog.get_actionType("savePhotoPriDev");
      var element = document.getElementById("bigPriDev");
      element.src = ""
    } else if (videoType == 1) {
      dialog.photoBtnClicked("subDev_");
      dialog.get_actionType("savePhotoSubDev");
      var element = document.getElementById("bigSubDev");
      element.src = ""
    } else if (videoType == 2) {
      dialog.get_actionType("singleReadBarcode");
    }
    this.setState({
      visible: false,
    });
  }
  componentDidMount() {
   
  }
  componentWillUnmount() { }

  render() {
    const { videoType, visible, idcard } = this.state;
    let okText = '拍照';
    if (videoType == 1) {
      okText = '拍照对比';
    } else if (videoType == 2) {
      okText = '二维码识别';
    }
    return (
      <Modal
        title={okText}
        width={650}
        mask={false}
        maskClosable={false}
        // confirmLoading={confirmLoading}
        visible={visible}
        onOk={() => this.handleOk()}
        onCancel={() => this.handleCancel()}
        destroyOnClose={true}
        cancelText="取消"
        okText={okText}
      >
        {videoType == 0 || videoType == 2 || videoType == 3? <img
          id="bigPriDev"
          width="600"
          height="300"
          border="0"
          classID="CLSID:26BA9E7F-78E9-4FB8-A05C-A4185D80D759"
        >
        </img> :
          <img
            id="bigSubDev"
            width="600"
            height="300"
            border="0"
            classID="CLSID:26BA9E7F-78E9-4FB8-A05C-A4185D80D759"
          >
          </img>}
      </Modal>
    );
  }
}
